// 文件上传处理函数模块

const db = require('../mysql/index')

const fs= require('fs')
const path = require('path')

// 上传图片
exports.uploadImg = (req, res) => {
    if (req.file) {
        fs.readFile(req.file.path, (err, data) => {
            if (err) return res.cc(err)
            const img = req.file.originalname.split('.')
            const imgType = img[img.length - 1]
            fs.writeFile(path.join(__dirname, '../uploads/', req.file.filename + `.${imgType}`), data, (err1) => {
                if (err1) return res.cc(err1)
                // 删除上传的二进制文件
                fs.unlink(req.file.path, (err2) => {
                    if (err2) console.log(err2);
                })
                console.log('上传成功');
                console.log(path.join(req.file.filename + `.${imgType}`));
                return res.send({
                    code: 200,
                    message: '上传成功',
                    // imgUrl: path.join(__dirname, '../uploads/', req.file.filename + `.${imgType}`)
                    // imgUrl: path.join('localhost/', req.file.filename + `.${imgType}`)
                    imgUrl: path.join(req.file.filename + `.${imgType}`)
                })
            })
        })
    } else {
        return res.cc('上传失败')
    }
}